<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px">
          <el-col :span="6">
            <el-form-item label="类型名称">
              <el-input
                v-model="listQuery.fdictname"
                clearable
                class="filter-item"
                placeholder="请输入类型名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button @click="handleFilter" type="primary">查找</el-button>
              <el-button @click="handleCreate" type="success">添加</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <!-- 查询结果 -->
        <JNPF-table v-loading="listLoading" :data="list">
          <el-table-column
            align="center"
            :width="buttonColor.operationTwo"
            label="操作"
            class-name="small-padding"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button type="text" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            :width="buttonColor.line"
            :index="indexMethod"
            align="center"
            label="序"
            type="index"
          />
          <el-table-column align="left" label="类型编号" prop="fdictno" />
          <el-table-column align="left" label="类型名称" prop="fdictname" />
          <el-table-column align="left" label="红外码库" prop="ftablename" />
        </JNPF-table>
        <paginations
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog
      :fullscreen="true"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      :title="textMap[dialogStatus]"
    >
    <el-tabs type="border-card">
      <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
        <el-row class="JNPF-common-search-box" :gutter="16">
          <el-form @submit.native.prevent label-width="80px" ref="dataForm" :rules="rules" :model="dataForm">
            <el-col :span="8">
               <el-form-item
              class="required"
              label="类型编号"
              prop="fdictno"
            >
              <el-input v-model="dataForm.fdictno" :disabled="dialogStatus != 'create'" @change="limits()"/>
            </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="红外码库" prop="ftablename">
              <el-input v-model="dataForm.ftablename" />
            </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编码" prop="fnumpre">
              <el-input v-model="dataForm.fnumpre" />
            </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="图片" prop="ficon2">
              <el-upload
                v-model="dataForm.ficon2"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                :data="formdata2(dataForm.fdictno)"
                class="avatar-uploader"
              >
                <img v-if="heddon" :src="dataForm.ficon2" class="avatar" style="width:40px;height:40px" />
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  style="font-size: 9px"
                  ></i>
              </el-upload>
            </el-form-item>
            </el-col>
            <el-col :span="8">
               <el-form-item
              class="el-form-item-small"
              label="类别"
              prop="ftype"
            >
              <el-select
                v-model="dataForm.ftype"
                class="filter-item"
                placeholder="请选择类别"
              >
                <el-option
                  v-for="(key, value) in frangeMap"
                  :key="key"
                  :label="key"
                  :value="value"
                />
              </el-select>
            </el-form-item>
            </el-col>
            <el-col v-show="dataForm.ftype === '0'" :span="8">
            <el-form-item label="插脚数量" prop="fmarkNum">
              <el-input v-model="dataForm.fmarkNum" />
            </el-form-item>
          </el-col>
          </el-form>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="明细表">
        <JNPF-table
                v-loading="listLoading"
                :data="dataForm.actions"
                 :height="screenHeight-230"
              >
                <el-table-column
                  :index="indexMethod"
                  align="center"
                  label="序"
                  type="index"
                />
                <el-table-column align="center" label="控制指令" prop="faction">
                  <template slot-scope="scope">
                  <el-input 
                    v-model="scope.row.faction" 
                    v-direction="{ x: 0, y: scope.$index,type:3}"
                  >
                  </el-input>
                </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="指令描述"
                  prop="fdescribe"
                >
                <template slot-scope="scope">
                  <el-input 
                    v-model="scope.row.fdescribe" 
                    v-direction="{ x: 1, y: scope.$index,type:3}"
                  >
                  </el-input>
                </template>
                </el-table-column>
                <el-table-column align="center" label="排序" prop="findex" />
                <el-table-column :formatter="formatsceneFlag" align="center" label="场景显示" prop="sceneFlag" />
              <el-table-column align="center" label="图片" prop="fscoreFlag">
                <template slot-scope="scope">
                  <el-upload
                v-model="scope.row.fscoreFlag"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                class="avatar-uploader"
              >
                <img v-if="heddon" :src="dataForm.ficon2" class="avatar" style="width:40px;height:40px" />
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  style="font-size: 9px"
                  ></i>
              </el-upload>
                </template>
              </el-table-column>
                <el-table-column
                  align="center"
                  :width="buttonColor.operationTwo"
                  label="操作"
                  class-name="small-padding"
                >
                  <template slot-scope="scope">
                    <el-button @click="handleDelete1(scope.row)" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </JNPF-table>
      </el-tab-pane>
    </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()" type="info">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData"
          >确定</el-button
        >
        <el-button v-else @click="updateData" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listdict, createdict, updatedict, deletedict } from "@/api/eqtDict";
import Pagination from "@/components/Pagination";
import moment from "moment";
import { uploadPath } from "@/api/room";
import { tableColor, titleColor,buttonColor } from "@/filters/index";

const frangeMap = {
  0: "排插",
  1: "设备",
};

export default {
  name: "STsEquipmentDict",
  components: { Pagination },
  filters: {
    frangeFilter(type) {
      return frangeMap[type];
    }
  },
  data() {
    return {
      panelHeight: 0,
      sceneFlagList: [
        { value: 1, label: "是" },
        { value: 0, label: "否" },
      ],
      buttonColor:buttonColor,
      isActive: true,
      screenHeight: document.body.clientHeight,
      actionsTmp: [],
      listTmp: [],
      heddon: false,
      heddonDetail: false,
      uploadPath,
      multipleSelection: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fdictname: undefined,
        ftablename: undefined,
        ftype: undefined,
        fmarkNum: undefined,
        ficon: undefined,
        sort: "create_time",
        order: "desc",
      },
      frangeMap,
      dataForm: {
        fdictno: undefined,
        fdictname: undefined,
        ftablename: undefined,
        ftype: undefined,
        fmarkNum: undefined,
        ficon: undefined,
        id: undefined,
        actions: [],
        ficon2: undefined,
        fnumpre: undefined,
      },
      dataForm1: {
        faction: undefined,
        fdescribe: undefined,
        findex: undefined,
        sceneFlag: undefined,
        fimage: undefined,
      },
      // actions: null,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        fdictno: [{ required: true, message: "类型编号不能为空" }],
        fdictname: [{ required: true, message: "类型名称不能为空" }],
        ftablename: [],
        ficon: [],
        fnumpre: [{min: 0, max: 6,message: "最多输入六个字符"}],
      },
      rules1: {
        faction: [{ required: true, message: "控制指令不能为空" }],
        fdescribe: [{ required: true, message: "指令描述不能为空" }],
      },
    };
  },
  created() {
    this.keyCode();
    this.panelHeight = document.documentElement.clientHeight-338
    this.getList();
  },
  methods: {
     //回车
    keyCode() {
      let direction = this.$getDirection();
      let _this=this;
      direction.on("keyup", function (e, val) {
        if (e.keyCode === 13) {
          if(val.y==_this.dataForm.actions.length-1)
          {
            _this.addrow(res=>{
               direction.next();
            })
          }
          else
          {
           direction.next();
          }
        }
        if (e.keyCode === 37) {
          direction.previous();
        }
        if (e.keyCode === 38) {
          direction.previousLine();
        }
        if (e.keyCode === 40) {
          direction.nextLine();
        }
        if (e.keyCode == 39) {
          direction.next();
        }
      });
    },
    //添加行
    addrow(callback){
      this.dataForm.actions.push({
        faction:"",
        findex:this.dataForm.actions.length+1,
        sceneFlag:"",
        fscoreFlag:""
      })
      setTimeout(()=>{
      callback(200)
      },300)
    },
    // 状态
    formatsceneFlag: function (row, column) {
      if (this.sceneFlagList) {
        for (let i = 0; i < this.sceneFlagList.length; i++) {
          if (row.sceneFlag == this.sceneFlagList[i].value) {
            return this.sceneFlagList[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    limits(){
      if(this.dataForm.fdictno !=undefined&&this.dataForm.fdictno !='' )
        {
          this.isActive = false;
        }
        else
        {
          this.isActive = true;
        }
    },

    //图片
    formdata3: function(faction) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
        return { 'ftype': '9', 'factionid':  this.dataForm.fdictno + faction}
    },
    handleAvatarSuccess1(res, file) {
      // this.dataForm.fimage = URL.createObjectURL(file.raw)
      this.dataForm1.fimage = res.data
      const time = new Date().getTime()
      this.dataForm1.fimage = `${this.dataForm1.fimage}?time=${time}`
      this.heddonDetail = true;
    },

    beforeAvatarUpload1(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },

  test(){
    if(this.isActive)
    {
      this.$notify.error({
          title: "失败",
          message: '请先输入类型编号',
      });
    }
  },
    datetimeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    getList() {
      this.listLoading = true;
      listdict(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        fdictname: undefined,
        ftablename: undefined,
        ftype: undefined,
        fmarkNum: undefined,
        ficon: undefined,
        id: undefined,
        fnumpre: undefined,
        actions: [],
      };
    },
    resetForm1(){
       this.dataForm1={
        faction: undefined,
        fdescribe: undefined,
        findex: undefined,
        sceneFlag: undefined,
        fimage: undefined,
      }
    },
    cancel() {
      this.heddon = false;
      this.heddonDetail = false;
      this.dialogFormVisible = false;
      this.list.forEach((v) => {
        if (v.fdictno === this.dataForm.fdictno) {
          this.dataForm = this.listTmp;
          this.dataForm.actions = this.actionsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },
    handleUpdate1() {
      this.dataForm1 = {};
      this.dataForm1.sceneFlag = 1
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },

    handleDelete1(row) {
      const index = this.dataForm.actions.indexOf(row);
      this.dataForm.actions.splice(index, 1);
    },
    // 弹窗点击关闭前的回调
    handleClose() {
      this.heddon = false;
      this.heddonDetail = false;
      this.dialogFormVisible = false;
      this.list.forEach((v) => {
        if (v.fdictno === this.dataForm.fdictno) {
          this.dataForm = this.listTmp;
          this.dataForm.actions = this.actionsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.addrow(res=>{})

       // 子表1
      this.handleUpdate1()
      this.resetForm1();
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id;
          this.dataForm.fupddate = new Date();
          createdict(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "添加设备类型成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dataForm.actions=new Array();
      this.dialogStatus = "update";
       this.addrow(res=>{})
      this.dialogFormVisible = true;
      this.actionsTmp = [];
      this.listTmp = row;
      if(row.ficon2){
        this.heddon = true;
      }
      row.actions.forEach((v) => {
        this.actionsTmp.push(v);
      });
      this.dataForm.ftype = this.dataForm.ftype.toString()
        // 子表1
      this.handleUpdate1()
      this.resetForm1();
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id;
          this.dataForm.fupddate = new Date();
          updatedict(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.fdictno === this.dataForm.fdictno) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新设备类型成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
      // 子表一添加编辑
    handleEdit1(row){
      this.dataForm1 = Object.assign({}, row)
      if(row.fimage){
        this.heddonDetail = true;
      }
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })

    },
    // 子表一编辑保存数据
    editData1() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          if(this.dataForm.actions.length > 0){
            let isAdd1 = true
            for (const v of this.dataForm.actions) {
                if (v.faction === this.dataForm1.faction) {
                  const index = this.dataForm.actions.indexOf(v)
                  this.dataForm.actions.splice(index, 1, this.dataForm1)
                  isAdd1 = false
                  break
                }
            }
            if(isAdd1){
                  this.dataForm.actions.push(this.dataForm1);
            }

          }else{
            this.dataForm.actions.push(this.dataForm1);
          }

            // 子表添加

            this.resetForm1()
            this.heddonDetail = false;
            // 清除验证
            this.$nextTick(() => {
              this.$refs["dataForm1"].clearValidate();
            });
        }
      });
    },
    cancle1(){
          this.resetForm1()
          this.heddonDetail = false;
          // 清除验证
          this.$nextTick(() => {
            this.$refs["dataForm1"].clearValidate();
          });
    },
    handleDelete(row) {
      this.$confirm("是否要删除设备类型", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletedict(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除设备类型成功",
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response,
            });
          });
      });
    },
    indexMethod(index) {
      index = index + 1;
      return index;
    },
    //图片
    formdata2: function (fdictno) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
      return { ftype: "4", fdictno: fdictno };
    },
    handleAvatarSuccess(res, file) {
      // this.dataForm.ficon2 = URL.createObjectURL(file.raw)
      this.dataForm.ficon2 = res.data;
      const time = new Date().getTime();
      this.heddon = true;
      this.dataForm.ficon2 = `${this.dataForm.ficon2}?time=${time}`;
    },

    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M; // isJPG &&
    },

    //*图片
  },
};
</script>